package com.main.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileReadOrSave {
    
	private Logger log=LoggerFactory.getLogger(this.getClass());
	/**
	 * 读取配置文件内容
	 * @param fileName
	 * @return
	 */
	public String getFileContent(String path,String fileName){
		log.info("读取文件路径："+path+"名称："+fileName);
		if(null==fileName){
			return null;
		}
		
		if(null!=path&&!path.endsWith(File.pathSeparator)){
			path+=File.pathSeparator;
		}
		
        try {
        	InputStream is=new FileInputStream(path+fileName);
        	InputStreamReader ir=new InputStreamReader(is,"UTF-8");
			BufferedReader br=new BufferedReader(ir);
			StringBuilder sb=new StringBuilder();
			String data=null;
			while(null!=(data = br.readLine())){
				sb.append(data+"\r\n");
			}
			is.close();
			ir.close();
			br.close();
			return sb.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 读取配置文件内容
	 * @param fileName
	 * @return
	 */
	public void saveFileContent(String path,String fileName,String content,boolean isAppend){
		log.info("保存文件路径："+path+"名称："+fileName);
		if(null==fileName){
			return;
		}
		if(null!=path){
			path=path.replace("\\", "/");
			if(!path.endsWith("/")&&!path.endsWith(File.separator)){
				path+=File.separator;
			}
		}
        try {
        	File pathFile=new File(path);
        	if(!pathFile.exists()){
        		log.info("文件夹不存在创建文件路径:"+pathFile.getAbsolutePath());
        		pathFile.mkdirs();
        	}
        	File file=new File(path+fileName);
        	if(!file.exists()){
        		log.info("文件不存在创建文件路径:"+file.getAbsolutePath());
        		file.createNewFile();
        		if(file.isDirectory()){
        			file.delete();
        			log.info("文件是个目录删除此目录");
        			return;
        		}
        	}
        	
        	FileOutputStream fs=new FileOutputStream(file,isAppend);
            OutputStreamWriter  ow=new OutputStreamWriter(fs,"UTF-8");
			BufferedWriter bw=new BufferedWriter(ow);
			bw.write(content);
			bw.close();
			ow.close();
			fs.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return;
	}
}
